package com.itheima.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;

public class MyInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取会话域对象中数据
        Object user = request.getSession().getAttribute("user");
        //判断用户名
        if(user==null){
            HashMap<String, String> errormap = new HashMap<>();
            errormap.put("error","先登录再访问");
            //设置响应乱码
            response.setContentType("application/json;charset=utf-8");
           //使用jackson将map集合转换成json响应给客户端
            ObjectMapper objectMapper=new ObjectMapper();
            objectMapper.writeValue(response.getWriter(),errormap);
            return false;

        }
        return true;
    }
}
